
package org.testfire.realm.converters;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

/**
 * A converter for the values on user which return Integer types instead of
 * booleans, when we need a boolean.
 * <p/>
 * Mostly an example of how to write and use converters.
 *
 * @author Geoff M. Granum
 * @version 1.0
 */
public class BoolConverter implements Converter {

	public BoolConverter() {
		super();
	}

	/**
	 * Return an Integer which represents a C style boolean value.
	 * If boolean.valueOf(String) is true, we set the value to 1, otherwise
	 * return an integer with value 0.
	 *
	 * @param facesContext FacesContext
	 * @param uIComponent  UIComponent
	 * @param string       A string representing a boolean value ('true' or 'false';
	 *                     however Boolean.valueOf only checks that the string equals 'true', anything else is
	 *                     false.
	 * @return Object An integer representing a boolean value.
	 */
	public Object getAsObject(FacesContext facesContext, UIComponent uIComponent, String string) {
		return Boolean.valueOf(string) ? 1 : 0;

	}

	/**
	 * Get the value of the object as a string. If the object passed is an Integer, we return
	 * true or false based on the C style boolean (true if value != 0).
	 *
	 * @param facesContext FacesContext
	 * @param uIComponent  UIComponent
	 * @param object       Object
	 * @return String If the object is an integer, 'true' if object.intValue != 0, false otherwise. If the object
	 *         is not an instance of Integer, we return object.toString().
	 */
	public String getAsString(FacesContext facesContext, UIComponent uIComponent, Object object) {
		if (object instanceof Integer) {
			return (Integer) object != 0 ? "true" : "false";
		}
		else {
			return object.toString();
		}
	}
}
